package model

import (
	"encoding/json"
	"gf-xb-api/cwt/consts"
	"strings"
)

// PageRequest ...分页请求参数
type PageRequest[T any] struct {
	PageCondition *PageCondition  `json:"pageCondition"`
	FilterGroup   *FilterGroup[T] `json:"filterGroup"`
}

// UnmarshallPageRequestJson ... 取消聚合Json
func (p *PageRequest[T]) UnmarshallPageRequestJson(jsonData []byte) (*PageRequest[T], error) {

	// 先Unmarshal下
	var res PageRequest[T]
	json.Unmarshal(jsonData, &res)

	// 再尝试解析filterGroup > groups
	var f any
	err := json.Unmarshal(jsonData, &f)
	if err != nil {
		return nil, err
	}

	m := f.(map[string]any)

	// 获取filterGroup.groups
	for k, v := range m {
		if strings.ToLower(k) != consts.ATTR_FILTERGROUP {
			continue
		}

		gMap := v.(map[string]any)

		var group *FilterGroup[T]
		res.FilterGroup = group.UnmarshallFilterGroupJson(gMap)
	}

	return &res, nil
}
